/**
 * Created by Junhua on 2018/8/21 for webview javascript bridge.
 */
function getQueryValByName (name) {//根据query获取参数
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);  //获取url中"?"符后的字符串并正则匹配
    var context = '';
    if (r) context = r[2];
    return context;
}

function qs(obj) {
    var res = '';
    var i = 0;
    for(var p in obj){
        res += p + '=' + obj[p] + '&' ;
        i++;
    }
    return res.substr(0,res.length - 1);
}

(function setupWebViewJavascriptBridge(callback) { /*这段代码是固定的，必须要放到js中*/
    axios.defaults.transformRequest = [function (data) {
        data = qs(data);
        return data;
    }];
    var platform = getQueryValByName('platform');
    console.log(platform);
    if(platform == 'ios'){
        if (window.WebViewJavascriptBridge) {
            return callback(WebViewJavascriptBridge);
        }
        if (window.WVJBCallbacks) {
            return window.WVJBCallbacks.push(callback);
        }
        window.WVJBCallbacks = [callback];
        var WVJBIframe = document.createElement('iframe');
        WVJBIframe.style.display = 'none';
        WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
    }else{
        if (window.WebViewJavascriptBridge) {
            callback(WebViewJavascriptBridge)
        } else {
            document.addEventListener(
                'WebViewJavascriptBridgeReady'
                , function() {
                    callback(WebViewJavascriptBridge)
                },
                false
            );
        }
    }
})(function(bridge) {
    bridge.registerHandler('callHandler', function(data, responseCallback) {
        var responseData = { 'Javascript Says':'I am Js, CallBack Now!!!!!' }
        responseCallback(responseData,data)
    })
    //默认接收
    bridge.init(function(message, responseCallback) {
        var responseData = 'js默认接收完毕，并回传数据给java';
        responseCallback(responseData); //回传数据给java
    });
})